package com.example.test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class completableFuture {
    public static void main(String[] args) {
        //使用线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        //开启子线程
        try {
            CompletableFuture.supplyAsync(() -> {
                System.out.println("开启子线程 " + Thread.currentThread().getName());
                //程序运行时间
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //返回值
                return "hello completableFuture";
            }, threadPool).whenComplete((v, e) -> {
                if (e == null) {
                    System.out.println("第二步，获取上一步数据：" + v);
                }
            }).exceptionally(e -> {
                e.printStackTrace();
                return null;
            });
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //必须关闭线程池，否则程序会一直运行
            threadPool.shutdown();
        }
        //主线程
        System.out.println("主线程正在运行。。。");
    }

}
